package com.aust.superTest;

import java.util.concurrent.locks.ReentrantLock;

// 测试Lock锁
public class TestLock implements Runnable {

    // 定义lock锁
    private final ReentrantLock lock = new ReentrantLock();

    // 票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            try {
                // 加锁
                lock.lock();
                if (ticketNums > 0) {
                    System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票");
                } else {
                    break;
                }
            } finally {
                // 解锁
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        TestLock testLock = new TestLock();

        new Thread(testLock, "小明").start();
        new Thread(testLock, "黄牛").start();
        new Thread(testLock, "老师").start();

    }

}
